package com.atwisdom.star.core.bsl.dataSource;

import com.alibaba.druid.pool.DruidDataSource;
import com.atwisdom.star.common.util.SpringContextUtil;
import com.atwisdom.star.config.DynamicDataSource;
import com.atwisdom.star.core.dao.pojo.TenantInfo;
import com.atwisdom.star.core.dao.service.TenantInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 动态数据源初始化
 */
@Slf4j
// @Configuration
// @AllArgsConstructor
public class DynamicDataSourceInit1 {

    private TenantInfoService tenantInfoService;

    @Bean
    public void initDataSource() {
        log.info("======初始化动态数据源=====");
        DynamicDataSource dynamicDataSource =  SpringContextUtil.getBean("dynamicDataSource");
        DruidDataSource master = SpringContextUtil.getBean("master");
        Map<Object, Object> dataSourceMap = new HashMap<>();
        dataSourceMap.put("master", master);

        List<TenantInfo> tenantList = tenantInfoService.list();
        for (TenantInfo tenantInfo : tenantList) {
            log.info(tenantInfo.toString());
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setDriverClassName(tenantInfo.getDatasourceDriver());
            dataSource.setUrl(tenantInfo.getDatasourceUrl());
            dataSource.setUsername(tenantInfo.getDatasourceUsername());
            dataSource.setPassword(tenantInfo.getDatasourcePassword());
            dataSource.setConnectProperties(master.getConnectProperties());
            dataSourceMap.put(tenantInfo.getTenantId(), dataSource);
        }
        // 设置数据源
        dynamicDataSource.setDataSources(dataSourceMap);
        /**
         * 必须执行此操作，才会重新初始化AbstractRoutingDataSource 中的 resolvedDataSources，也只有这样，动态切换才会起效
         */
        dynamicDataSource.afterPropertiesSet();
    }
}
